//
//  EditViewController.m
//  ios通讯录(9.0)
//
//  Created by apple on 16/9/11.
//  Copyright © 2016年 LWB. All rights reserved.
//

#import "EditViewController.h"
#import "JKContactModel.h"
@interface EditViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UIButton *savebtn;
- (IBAction)saveAction:(id)sender;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *edit;

- (IBAction)editAction:(UIBarButtonItem *)sender;

@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nameField.text = self.contactModel.name;
    self.phoneField.text = self.contactModel.phone;
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.nameField];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.phoneField];
}
-(void)textChange{
    //修改按钮的点击状态
    self.savebtn.enabled=(self.nameField.text.length&&self.phoneField.text.length);
}

//关闭键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.nameField resignFirstResponder];
    [self.phoneField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//保存数据
- (IBAction)saveAction:(id)sender {
    //1、关闭当前页面
    [self.navigationController popViewControllerAnimated:YES];
    //2、通知代理
    if ([self.delegate respondsToSelector:@selector(enditViewController:didSaveContact:)]) {
        //更新数据模型
        self.contactModel.name = self.nameField.text;
        self.contactModel.phone = self.phoneField.text;
        [self.delegate enditViewController:self didSaveContact:self.contactModel];
    }
}


//编辑按钮响应
- (IBAction)editAction:(UIBarButtonItem *)sender {
    if (self.nameField.enabled) {
        self.nameField.enabled=NO;
        self.phoneField.enabled=NO;
        [self.view endEditing:YES];
        self.savebtn.hidden = YES;
        sender.title = @"编辑";
        //还原回原来的数据
        self.nameField.text = self.contactModel.name;
        self.phoneField.text = self.contactModel.phone;
    }else{
        self.nameField.enabled=YES;
        self.phoneField.enabled=YES;
        [self.view endEditing:YES];
        self.savebtn.hidden = NO;
        sender.title = @"取消";
    }
}
@end
